import { useControllableValue } from 'ahooks';
import { Tree } from 'antd';

import { Assignee, RoleDataNode, UserSelectProps } from '..';
import Avatar from '../avatar';
import styles from './index.module.scss';

export type RolePanelProps = Pick<UserSelectProps, 'value' | 'onChange' | 'mode'> & {
  /** 角色列表 */
  roleList?: RoleDataNode[];
};

const RolePanel: React.FC<RolePanelProps> = ({ roleList, mode, ...rest }) => {
  // 是否多选
  const isMultiple = mode === 'multiple' || mode === 'tags';
  const [value, setValue] = useControllableValue<UserSelectProps['value']>(rest);

  const onSelect: React.ComponentProps<typeof Tree<RoleDataNode>>['onSelect'] = (_, e) => {
    if (isMultiple) {
      setValue(e.selectedNodes);
    } else {
      setValue(e.selectedNodes[e.selectedNodes.length - 1]);
    }
  };
  const onCheck: React.ComponentProps<typeof Tree<RoleDataNode>>['onCheck'] = (_, e) => {
    if (isMultiple) {
      setValue(e.checkedNodes);
    } else {
      setValue(e.checkedNodes[e.checkedNodes.length - 1]);
    }
  };

  const titleRender: React.ComponentProps<typeof Tree<RoleDataNode>>['titleRender'] = (node) => {
    return (
      <div className="select-item">
        <Avatar size={36} className="select-item-avatar">
          {node.title as string}
        </Avatar>
        <div className="select-item-name">{node.title as string}</div>
      </div>
    );
  };

  return (
    <div className={styles['role-panel']}>
      <Tree<RoleDataNode>
        treeData={roleList}
        blockNode
        selectable={false}
        showLine
        multiple
        checkable
        checkedKeys={
          isMultiple
            ? value
              ? (value as Assignee[]).map((v) => v.id)
              : []
            : value
              ? [(value as Assignee).id]
              : []
        }
        onCheck={onCheck}
        onSelect={onSelect}
        titleRender={titleRender}
      />
    </div>
  );
};

export default RolePanel;
